package thread.unsafeExample;



/**
 * 3个线程对 Account对象进行操作
 * 1.1个存钱线程，为了让程序持续运行
 * 2.2个取钱线程，由于判断和取款并不是原子操作，因此可以能产生线程安全问题。
 *
 * Created by E440 on 2017/4/19.
 */
public class DrawSaveMoneyDemo {
    public static void main(String[] args) {
       final UnsafeAccount account=new UnsafeAccount(1,100);//线程不安全
        //  final SafeAccount account=new SafeAccount(1,100);//线程不安全
        final double drawMoney=30;
        final double saveMoney=10;
        final boolean[] flags={true};//tip: 内部类只能访问 final类型数据
        //存钱线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (flags[0]){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if(account.getAmount()<0){
                        break;
                    }
                    account.save(saveMoney);
                    //System.out.println("save thread : "+account);
                }
            }
        }).start();

        //取钱线程-1
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (flags[0]){
                    try {
                        Thread.sleep(30);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    account.draw(drawMoney);
                    //System.out.println("draw thread a: "+account);
                    if(account.getAmount()<0){
                        flags[0]=false;
                    }
                }

            }
        }).start();

        //取钱线程-2
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (flags[0]){
                    try {
                        Thread.sleep(30);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    account.draw(drawMoney);
                    //System.out.println("draw thread b : "+account);
                    if(account.getAmount()<0){
                        flags[0]=false;
                    }
                }

            }
        }).start();


    }
}
